#!/bin/bash

# ========================================
# 智能排课系统 - 一键修复脚本
# 直接在服务器上运行
# ========================================

echo "========================================"
echo "智能排课系统 - 登录问题一键修复"
echo "========================================"
echo ""

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# ========================================
# 1. 检查当前状态
# ========================================
echo -e "${YELLOW}【步骤 1/6】检查当前状态...${NC}"
echo ""

echo "1.1 检查 Nginx 状态："
systemctl is-active nginx
if [ $? -eq 0 ]; then
    echo -e "${GREEN}✅ Nginx 正在运行${NC}"
else
    echo -e "${RED}❌ Nginx 未运行${NC}"
fi
echo ""

echo "1.2 检查后端进程："
if ps aux | grep -v grep | grep "java.*pake.jar" > /dev/null; then
    echo -e "${GREEN}✅ 后端服务正在运行${NC}"
    ps aux | grep -v grep | grep "java.*pake.jar" | awk '{print "进程ID:", $2, "启动时间:", $9}'
else
    echo -e "${RED}❌ 后端服务未运行${NC}"
fi
echo ""

echo "1.3 检查前端文件："
if [ -d "/opt/paike/frontend" ]; then
    echo -e "${GREEN}✅ 前端目录存在${NC}"
    ls -lh /opt/paike/frontend/index.html 2>/dev/null
else
    echo -e "${RED}❌ 前端目录不存在${NC}"
fi
echo ""

read -p "按回车键继续..." 

# ========================================
# 2. 备份旧配置
# ========================================
echo ""
echo -e "${YELLOW}【步骤 2/6】备份旧配置...${NC}"
if [ -f "/etc/nginx/conf.d/paike.conf" ]; then
    backup_file="/etc/nginx/conf.d/paike.conf.bak.$(date +%Y%m%d%H%M%S)"
    cp /etc/nginx/conf.d/paike.conf "$backup_file"
    echo -e "${GREEN}✅ 已备份到: $backup_file${NC}"
else
    echo -e "${YELLOW}⚠ 没有找到旧配置文件${NC}"
fi
echo ""

# ========================================
# 3. 写入正确的 Nginx 配置
# ========================================
echo -e "${YELLOW}【步骤 3/6】写入正确的 Nginx 配置...${NC}"

cat > /etc/nginx/conf.d/paike.conf << 'EOF'
server {
    listen 80;
    server_name 172.16.29.198;

    # 前端静态文件
    root /opt/paike/frontend;
    index index.html;

    # 前端路由（SPA）
    location / {
        try_files $uri $uri/ /index.html;
    }

    # 后端API代理（关键！）
    location /api/ {
        proxy_pass http://127.0.0.1:8090/;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        
        # CORS 头（可选，后端已有 @CrossOrigin）
        add_header Access-Control-Allow-Origin *;
        add_header Access-Control-Allow-Methods 'GET, POST, PUT, DELETE, OPTIONS';
        add_header Access-Control-Allow-Headers 'Content-Type, Authorization';
    }
}
EOF

echo -e "${GREEN}✅ 配置文件已写入${NC}"
echo ""

# ========================================
# 4. 测试并重启 Nginx
# ========================================
echo -e "${YELLOW}【步骤 4/6】测试并重启 Nginx...${NC}"

# 测试配置
nginx -t
if [ $? -eq 0 ]; then
    echo -e "${GREEN}✅ Nginx 配置测试通过${NC}"
    
    # 重启 Nginx
    systemctl restart nginx
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}✅ Nginx 重启成功${NC}"
    else
        echo -e "${RED}❌ Nginx 重启失败${NC}"
        exit 1
    fi
else
    echo -e "${RED}❌ Nginx 配置测试失败${NC}"
    exit 1
fi
echo ""

# ========================================
# 5. 检查防火墙
# ========================================
echo -e "${YELLOW}【步骤 5/6】检查防火墙...${NC}"

if systemctl is-active firewalld > /dev/null 2>&1; then
    echo "防火墙正在运行，检查80端口..."
    
    if firewall-cmd --list-ports | grep "80/tcp" > /dev/null; then
        echo -e "${GREEN}✅ 80端口已开放${NC}"
    else
        echo "开放80端口..."
        firewall-cmd --zone=public --add-port=80/tcp --permanent
        firewall-cmd --reload
        echo -e "${GREEN}✅ 已开放80端口${NC}"
    fi
else
    echo -e "${YELLOW}⚠ 防火墙未运行${NC}"
fi
echo ""

# ========================================
# 6. 测试登录接口
# ========================================
echo -e "${YELLOW}【步骤 6/6】测试登录接口...${NC}"
echo ""

echo "6.1 测试后端直接访问（确认后端正常）："
backend_response=$(curl -s -X POST "http://127.0.0.1:8090/admin/login" \
  -H "Content-Type: application/json" \
  -d '{"adminNo":"admin","password":"123456"}')

if echo "$backend_response" | grep -q "code"; then
    echo -e "${GREEN}✅ 后端服务正常${NC}"
    echo "响应: $backend_response"
else
    echo -e "${RED}❌ 后端服务异常${NC}"
    echo "响应: $backend_response"
fi
echo ""

echo "6.2 测试通过 Nginx 访问（前端实际使用）："
nginx_response=$(curl -s -X POST "http://172.16.29.198/api/admin/login" \
  -H "Content-Type: application/json" \
  -d '{"adminNo":"admin","password":"123456"}')

if echo "$nginx_response" | grep -q "code"; then
    echo -e "${GREEN}✅ Nginx 代理正常${NC}"
    echo "响应: $nginx_response"
else
    echo -e "${RED}❌ Nginx 代理异常${NC}"
    echo "响应: $nginx_response"
fi
echo ""

# ========================================
# 完成
# ========================================
echo ""
echo "========================================"
echo -e "${GREEN}✅ 修复完成！${NC}"
echo "========================================"
echo ""
echo "【访问地址】"
echo -e "${GREEN}✅ 正确地址: http://172.16.29.198${NC}"
echo ""
echo -e "${RED}❌ 不要访问:${NC}"
echo "   http://172.16.29.198:8090"
echo "   http://172.16.29.198:3000"
echo ""
echo "========================================"
echo ""
echo "【测试账号】"
echo "管理员: admin / 123456"
echo "学生: 20220001 / 123456"
echo "教师: T001 / 123456"
echo ""
echo "========================================"
echo ""
echo "【如果还有问题】"
echo "查看 Nginx 日志:"
echo "  tail -50 /var/log/nginx/error.log"
echo ""
echo "查看后端日志:"
echo "  tail -100 /opt/paike/backend/app.log"
echo ""
echo "重启后端服务:"
echo "  cd /opt/paike/backend"
echo "  ps aux | grep java | grep -v grep | awk '{print \$2}' | xargs kill -9"
echo "  nohup java -jar pake.jar > app.log 2>&1 &"
echo "========================================"








